/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tt.VorlesungenService;

import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import tt.Exception.EntityServiceException;
import tt.model.*;
//import tt.VorlesungenService.UniqueIDGenerator;

//        config.PersistenceUnitProperties;
/**
 *
 * @author andi
 */
@Stateful
public class EntityService {

    @PersistenceContext
    private EntityManager em;

    public EntityService() {
    }//end constructor

    public String createCourseSchedule(int idSemester)
            throws EntityServiceException {
        //32-stellige ID zum Speichern wird generiert
        String idSchedule = new UniqueIDGenerator().getNewID();


        Query myQuery = null;
        try {
            //Hole Semesterobjekt anhand der übergebenen ID
            myQuery = em.createNamedQuery("Semester.findByIdsemester");


            myQuery.setParameter("idsemester", idSemester);
            Semester currentSemester = (Semester) myQuery.getSingleResult();



            //hole alle mit dem Semester verknüpften Standardvorlesungen
            Collection<Lecture> myLectureCollection = currentSemester.getLectureCollection();
            Lecture tempLecture;
            //Diese Collection enthält alle LectureDates zur aktuellen Lecture
            Collection<Lecturedate> tempLectureDateCollection;
            Lecturedate tempdate;
            //Diese Collection soll beim Durchlauf der Schleife mit allen LectureDates gefüllt werden
            Collection<Lecturedate> myLectureDatesCollection = new ArrayList();
            Lecturedate tempLecturedate;

            //Durchlaufe Lectures
            for (Iterator<Lecture> it = myLectureCollection.iterator(); it.hasNext();) {
                tempLecture = it.next();

                //Durchlaufe Lecturedates
                for (Iterator<Lecturedate> itdate = tempLecture.getLecturedateCollection().iterator(); itdate.hasNext();) {

                    //Hier wird nur eine Kopie des eigentlichen Lecturedate Objektes hinzugefügt.
                    //das Original macht Probleme und verwirrt die Persistenceeinheit
                    tempLecturedate = itdate.next();
                    tempLecturedate = tempLecturedate.getCopy();
                    myLectureDatesCollection.add(tempLecturedate);

                }//endfor
            }//end for



            Courseschedule currentCourseSchedule = new Courseschedule();
            currentCourseSchedule.setIdcourseschedule(idSchedule);
            currentCourseSchedule.setLecturedateCollection(myLectureDatesCollection);

            Courseofstudy courseofstudy = new Courseofstudy();



            em.persist(currentCourseSchedule);
            return idSchedule;

        } catch (Exception Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": createCourseSchedule(" + idSemester + ", " + idSchedule + "))");
        }//endtry


    }//end method

    public void removeLectureDateFromCourseschedule(Courseschedule mySchedule, int iddate)
            throws EntityServiceException {
        Collection<Lecturedate> myDateCol = mySchedule.getLecturedateCollection();
        Lecturedate currentLecturedate;
        for (Iterator<Lecturedate> it = myDateCol.iterator(); it.hasNext();) {
            currentLecturedate = it.next();
            if (currentLecturedate.getIdlecturedate() == iddate) {
                it.remove();
                break;
            }//endif

        }//endfor

        try {


            //        Logger.getLogger(EntityService.class.getName()).log(Level.INFO, myDateCol.toString());
            em.merge(mySchedule);
        } catch (Exception Ex) {
            Logger.getLogger(EntityService.class.getName()).log(Level.INFO, Ex.toString());
            throw new EntityServiceException(Ex.getMessage() + ": removeLectureDateFromCourseschedule(" + iddate + ", " + mySchedule.getIdcourseschedule() + "))");
        }//endtry


    }//endmethod

    public void addLectureToCourseschedule(Courseschedule mySchedule, int idLecture)
            throws EntityServiceException {

        Collection<Lecturedate> myLectureDatesCollection = mySchedule.getLecturedateCollection();


        Query myQuery;
        Lecture currentLecture;
        try {
            //Hole Lectureobjekt anhand von ID
            myQuery = em.createNamedQuery("Lecture.findByIdlecture");
            myQuery.setParameter("idlecture", idLecture);
            currentLecture = (Lecture) myQuery.getSingleResult();
            Lecturedate tempLecturedate = null;

            boolean update = false; //nur wenn auch wirklich eine Änderung durchlaufen wird, merge Befehl ausführen
            //Durchlaufe Lecturedates zum einzelnen Hinzufügen zum Vorlesungsplan
            for (Iterator<Lecturedate> itdate = currentLecture.getLecturedateCollection().iterator(); itdate.hasNext();) {

                //Hier wird nur eine Kopie des eigentlichen Lecturedate Objektes hinzugefügt.
                //das Original macht Probleme und verwirrt die Persistenceeinheit
                tempLecturedate = itdate.next();

                //nur wenn die angegeben Lecture noch nicht enthalten ist, wird sie hinzugefügt
                if (myLectureDatesCollection.contains(tempLecturedate) == false) {
                    update = true;
                    tempLecturedate = tempLecturedate.getCopy();
                    myLectureDatesCollection.add(tempLecturedate);
                }//endif

            }//endfor

            //Logger.getLogger(EntityService.class.getName()).log(Level.INFO, myLectureDatesCollection.toString());
            if (update == true) {
                em.merge(mySchedule);
            }//endif
        } catch (Exception Ex) {
            Logger.getLogger(EntityService.class.getName()).log(Level.WARNING, Ex.getMessage());
            throw new EntityServiceException(Ex.getMessage() + ": addLectureToCourseschedule(" + idLecture + ", " + mySchedule.getIdcourseschedule() + "))");
        }//endtry


    }//endmethod

    public Courseofstudy getCourseOfStudyByIdCourse(String idcourse)
            throws EntityServiceException {

        Courseofstudy myCourse = null;
        try {
            Query myQuery = em.createNamedQuery("Courseofstudy.findByIdcourse");
            myQuery.setParameter("idcourse", Integer.parseInt(idcourse));

            myCourse = (Courseofstudy) myQuery.getSingleResult();
        } catch (Exception Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": getCourseOfStudyByCoursename(" + idcourse + ")");
        }//endtry
        return myCourse;


    }//end method

    public Collection<Lecture> getLectureCollection()
            throws EntityServiceException {

        Collection<Lecture> myCol = null;
        Query myQuery;
        try {
            myQuery = em.createNamedQuery("Lecture.findAll");
            List<Lecture> myList = myQuery.getResultList();
            myCol = myList;

        } catch (Exception Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": getLectureCollection()");
        }        //endtry


        return myCol;
    }//end getLectureList

    public Lecturedate getLectureDateByIDLectureDate(int idLecutureDate)
            throws EntityServiceException {

        Lecturedate myDate = null;
        try {
            Query myQuery = em.createNamedQuery("Lecturedate.findByIdlecturedate");
            myQuery.setParameter("idlecturedate", idLecutureDate);

            myDate = (Lecturedate) myQuery.getSingleResult();
        } catch (javax.persistence.NoResultException Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": getLectureDateByIDLectureDate(" + idLecutureDate + ")");
        } catch (javax.ejb.EJBException Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": getLectureDateByIDLectureDate(" + idLecutureDate + ")");
        } catch (Exception Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": getLectureDateByIDLectureDate(" + idLecutureDate + ")");
        }//endtry


        return myDate;

    }//end getLectureDate

    public Lecture getLectureByIDLecture(int idLecuture)
            throws EntityServiceException {

        Query myQuery;
        Lecture myLecture = null;
        try {
            myQuery = em.createNamedQuery("Lecture.findByIdlecture");
            myQuery.setParameter("idlecture", idLecuture);
            myLecture = (Lecture) myQuery.getSingleResult();
        } catch (javax.persistence.NoResultException Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": getLectureByIDLecture(" + idLecuture + ")");
        } catch (javax.ejb.EJBException Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": getLectureByIDLecture(" + idLecuture + ")");
        } catch (Exception Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": getLectureByIDLecture(" + idLecuture + ")");
        }//endtry



        return myLecture;

    }//end getLecturee

    public Courseschedule getCourseScheduleByIDCourseSchedule(String id)
            throws EntityServiceException {

        
        Courseschedule mySchedule = null;
        Query myQuery = null;
        
        try {
            myQuery = em.createNamedQuery("Courseschedule.findByIdcourseschedule");
            myQuery.setParameter("idcourseschedule", id);

            mySchedule = (Courseschedule) myQuery.getSingleResult();

        }  catch (Exception Ex) {
            
            throw new EntityServiceException(Ex.getMessage() + ": getCourseScheduleByIDCourseSchedule(" + id + ")");
        }//endtry

        return mySchedule;
    }//end method getCourseSchedule

    public Collection<Courseofstudy> getCourseOfStudyCollection()
            throws EntityServiceException {

        Collection<Courseofstudy> myCol = null;
        Query myQuery = null;
        try {
            myQuery = em.createNamedQuery("Courseofstudy.findAll");
            List<Courseofstudy> myList = myQuery.getResultList();
            myCol = myList;

        } catch (javax.persistence.NoResultException Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": getCourseOfStudyCollection()");
        } catch (javax.ejb.EJBException Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": getCourseOfStudyCollection()");
        } catch (Exception Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": getCourseOfStudyCollection()");
        }//endtry


        return myCol;
    }//end getCourseofStudyList

    public Collection<Semester> getSemesterCollection()
            throws EntityServiceException {//Query myQuery = em.createNativeQuery("Select * from Semester");

        Collection<Semester> myCol = null;
        Query myQuery = null;
        try {
            myQuery = em.createNamedQuery("Semester.findAll");
            List myList = myQuery.getResultList();
            myCol = myList;

        } catch (javax.persistence.NoResultException Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": getSemesterCollection()");
        } catch (javax.ejb.EJBException Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": getSemesterCollection()");
        } catch (Exception Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": getSemesterCollection()");
        }//endtry



        return myCol;
    }//end method getSemesterCol

    public Semester getSemesterByIDSemester(int idsemester)
            throws EntityServiceException {
        Query myQuery = null;
        Semester currentSemester = null;
        try {
            myQuery = em.createNamedQuery("Semester.findByIdsemester");
            myQuery.setParameter("idsemester", idsemester);
            currentSemester = (Semester) myQuery.getSingleResult();
            return currentSemester;

        } catch (Exception Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": getSemesterByIDSemester()");
        }//endtry

    }//end method

    public General getGeneralSettingsByIDGeneral(int idgeneral)
            throws EntityServiceException {

        General myGeneralSettings;
        try {
            Query myQuery = em.createNamedQuery("General.findByIdgeneral");
            myQuery.setParameter("idgeneral", idgeneral);

            myGeneralSettings = (General) myQuery.getSingleResult();
        } catch (Exception Ex) {
            throw new EntityServiceException(Ex.getMessage() + ": getGeneralSettingsByIDGeneral(" + idgeneral + ")");
        }//endtry
        return myGeneralSettings;


    }//end method

    public boolean scheduleExists(String idschedule) {

        Query myQuery = em.createNamedQuery("Courseschedule.findByIdcourseschedule");
        myQuery.setParameter("idcourseschedule", idschedule);
        try {
            List<Courseschedule> MyScheduleCol = myQuery.getResultList();
            if (MyScheduleCol.size() > 0) {
                return true;
            } else {
                return false;
            }//end if

        } catch (Exception Ex) {

            return false;
        }//end try


    }//end method

   
    public boolean deleteCourseschedule(Courseschedule mySchedule)
            {

        try {

            Query query = em.createNamedQuery("Courseschedule.deleteByIdcourseschedule");
            query.setParameter("idcourseschedule", mySchedule.getIdcourseschedule());
            int deleted = query.executeUpdate();
            if (deleted == 1) {
                Logger.getLogger(EntityService.class.getName()).log(Level.INFO, "delted: " + true);
                return true;
            } else {
                Logger.getLogger(EntityService.class.getName()).log(Level.INFO, "delted: " + false);
                return false;
            }// endi if

            
        } catch (Exception Ex) {
            Logger.getLogger(EntityService.class.getName()).log(Level.INFO, Ex.toString());
            return false;
        }//end try


    }//end method
    
    public Collection<Lecture> getLectureCollectionbyCourseSchedule(Courseschedule mySchedule) {   // Returntype: Collection<Lecture>
        
        Collection<Lecture> myCol = new ArrayList();

        Lecturedate tempLecturdate;
        Lecture tempLecture;
        Collection<Lecturedate> myLectureDateCollection = mySchedule.getLecturedateCollection();
        for (Iterator<Lecturedate> it = myLectureDateCollection.iterator(); it.hasNext();) {
            tempLecturdate = it.next();
            tempLecture = tempLecturdate.getLecture().getCopy();
            if (myCol.contains(tempLecture) == false) {
                myCol.add(tempLecture);
            }//endif 
        }//endfor

        //myCol sortieren
        Collections.sort((List<Lecture>) myCol, Lecture.SortByExamDate);

        return myCol;
    }//end mehtod
    
}//end class
